package com.yueya.system.controller;

import com.yueya.auth.config.AuthProperties;
import com.yueya.auth.utils.JwtUtil;
import com.yueya.auth.utils.RequestUtil;
import com.yueya.auth.utils.UserInfoUtil;
import com.yueya.common.base.BaseController;
import com.yueya.common.web.RestResult;
import com.yueya.system.dao.tables.pojos.TokenManageDO;
import com.yueya.system.service.SysTokenService;
import io.jsonwebtoken.Claims;
import io.jsonwebtoken.Jws;
import io.jsonwebtoken.JwtException;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.RequestBody;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;

import javax.servlet.http.HttpServletRequest;

import java.security.NoSuchAlgorithmException;
import java.security.spec.InvalidKeySpecException;
import java.util.Map;

import static com.yueya.auth.config.AuthConstant.LOGIN_FAIL_MESSAGE;
import static com.yueya.auth.config.AuthConstant.TOKEN_NAME;

@RestController
public class LoginController extends BaseController {
    @Autowired
    private AuthProperties properties;

    @Autowired
    private SysTokenService tokenService;

    @RequestMapping("login")
    public RestResult login(HttpServletRequest request){
        if(UserInfoUtil.getPrincipal()!=null){
            return RestResult.OK("已登录");
        }
        String message = (String) request.getAttribute(LOGIN_FAIL_MESSAGE);
        if(message!=null){
            return RestResult.ERROR(message);
        }
        return RestResult.ERROR("未登录,请先登录");
    }


    @RequestMapping("token")
    public RestResult toke(@RequestBody Map<String,String> authData, HttpServletRequest request){
        String token = authData.get("token");
        if (!properties.isJwtMode() || token == null){
            return null;
        }
        try {
            String host = RequestUtil.getRemoteAddr(request);
            String agent = RequestUtil.getUserAgent(request);
            String refreshToken = tokenService.getRefreshToken(token,host,agent);
            if (refreshToken != null){
                return RestResult.OkWithData(refreshToken);
            }else {
                return RestResult.ERROR("请重新登录");
            }
        } catch (InvalidKeySpecException|NoSuchAlgorithmException e) {
            logger.warn("无效key",e);
            return RestResult.ERROR("解析token异常");
        }catch (JwtException e) {
            logger.warn("无效token",e);
            return RestResult.ERROR("无效token");
        }
    }



}
